package com.yaoq.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @ClassName ProxyFactory
 * @Description TODO
 * @Author yaoqiang
 * @Date 2020/9/1 11:38
 * @Version 1.0
 */
public class ProxyFactory implements MethodInterceptor {
    private Object target;

    public ProxyFactory(Object target) {
        this.target = target;
    }
    //返回一个代理对象是target的代理对象

    /**
     * 创建一个工具类
     * 设置父类，回调函数，创建子类对象
     *
     * @return
     */
    public Object getProxyInstance() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("Cglib代理");
        Object returlVal = method.invoke(target, objects);
        System.out.println("Cglib代理模式-提交");
        return returlVal;
    }
}
